package com.smedi.ismedi.authoritymanagement.core.infrastructure.handler;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: xulinjun
 * @Date: 2021-7-22 20:47
 */
@Slf4j
@MappedTypes({List.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class ListTypeHandler extends BaseTypeHandler<List> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSONArray.toJSONString(list));
    }

    @Override
    public List getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String sqlJson = resultSet.getString(columnName);
        if (null != sqlJson) {
            JSONArray array = JSONArray.parseArray(sqlJson);
            return array.parseArray(array.toJSONString(), Object.class);
        }
        return null;
    }

    @Override
    public List getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String sqlJson = resultSet.getString(columnIndex);
        if (null != sqlJson) {
            JSONArray array = JSONArray.parseArray(sqlJson);
            return array.parseArray(array.toJSONString(), Object.class);
        }
        return null;
    }

    @Override
    public List getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String sqlJson = callableStatement.getString(columnIndex);
        if (null != sqlJson) {
            JSONArray array = JSONArray.parseArray(sqlJson);
            return array.parseArray(array.toJSONString(), Object.class);
        }
        return null;
    }
}
